package com.ruoyi.back.service.impl

import cn.hutool.core.util.StrUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.ruoyi.app.common.*
import com.ruoyi.back.domain.ChannelFreeTemplate
import com.ruoyi.back.domain.SystemNotice
import com.ruoyi.back.domain.Template
import com.ruoyi.back.domain.TemplateComment
import com.ruoyi.back.domain.dto.TemplateSearchDto
import com.ruoyi.back.domain.v3.PicTemplateFaceService
import com.ruoyi.back.enums.CheckStatusEnum
import com.ruoyi.back.mapper.ChannelFreeTemplateMapper
import com.ruoyi.back.mapper.TemplateMapper
import com.ruoyi.back.service.ChannelManagerService
import com.ruoyi.back.service.TemplateCategoryService
import com.ruoyi.back.service.TemplateCommentService
import com.ruoyi.back.service.TemplateService
import com.ruoyi.common.core.page.TableSupport
import com.ruoyi.util.addPicTemplate
import com.ruoyi.util.addVideoTemplate
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class TemplateServiceImpl : ServiceImpl<TemplateMapper, Template>(), TemplateService {

    @Autowired
    private lateinit var templateCategoryService: TemplateCategoryService

    @Autowired
    private lateinit var templateCommentService: TemplateCommentService

    @Autowired
    private lateinit var picTemplateFaceService: PicTemplateFaceService

    @Autowired
    private lateinit var channelFreeTemplateMapper: ChannelFreeTemplateMapper

    @Autowired
    private lateinit var channelManagerService: ChannelManagerService

    override fun saveTemplate(template: Template): Data<Boolean> =
        template.id?.run {
            Ok("更新成功", run {
                template.takeIf { it.freeTest!! }
                    ?.run {
                        channelFreeTemplateMapper.delete(
                            KtQueryWrapper(ChannelFreeTemplate::class.java)
                                .eq(ChannelFreeTemplate::templateId, template.id)
                                .eq(ChannelFreeTemplate::templateType, template.type)
                        )

                        template.freeChannelIds!!.split(",").takeIf { it.isNotEmpty() }
                            ?.run {
                                forEach {
                                    channelFreeTemplateMapper.insert(ChannelFreeTemplate().apply {
                                        channelId = it.toLong()
                                        templateId = template.id
                                        templateType = template.type
                                    })
                                }
                            }
                    }
                    ?: run {
                        channelFreeTemplateMapper.delete(
                            KtQueryWrapper(ChannelFreeTemplate::class.java)
                                .eq(ChannelFreeTemplate::templateId, template.id)
                                .eq(ChannelFreeTemplate::templateType, template.type)
                        )
                    }

                updateById(template)
            })
        } ?: kotlin.run {
            Ok("保存成功", run {

                save(template.apply {
                    template.type.takeIf { it == 2 }?.run {
                        addPicTemplate(template.content!!) { picTemplateFaces, s ->
                            picTemplateId = s
                            picTemplateFaces?.run { picTemplateFaceService.saveBatch(this) }
                        }
                    }
                    template.type.takeIf { it == 1 }?.run {
                        //requestId = addVideoTemplate(template.content!!)
                        requestStatus = 0
                    }
                })

                template.takeIf { it.freeTest!! }?.run {
                    template.freeChannelIds!!.split(",").takeIf { it.isNotEmpty() }
                        ?.run {
                            forEach {
                                channelFreeTemplateMapper.insert(ChannelFreeTemplate().apply {
                                    channelId = it.toLong()
                                    templateId = template.id
                                    templateType = template.type
                                })
                            }
                        }
                }
                true
            })
        }

    override fun templatePage(templateSearchDto: TemplateSearchDto): PageData<Template> =
        TableSupport.buildPageRequest().let { pageDomain ->
            page(Page(pageDomain.pageNum.toLong(), pageDomain.pageSize.toLong()), KtQueryWrapper(Template::class.java)
                .apply {
                    eq(StrUtil.isNotBlank(templateSearchDto.title), Template::title, templateSearchDto.title)
                    eq(Template::type, templateSearchDto.type)
                    eq(templateSearchDto.categoryId != null, Template::categoryId, templateSearchDto.categoryId)
                    gt(
                        StrUtil.isNotBlank(templateSearchDto.beginDate),
                        SystemNotice::sendTime,
                        templateSearchDto.beginDate.date()
                    )
                    lt(
                        StrUtil.isNotBlank(templateSearchDto.endDate),
                        SystemNotice::sendTime,
                        templateSearchDto.endDate.date()
                    )
                    orderByDesc(Template::createTime)
                })
                .let { page: Page<Template> ->
                    page.apply {
                        records = page.records.takeIf { it.isNotEmpty() }
                            ?.run {
                                map {
                                    it.apply {
                                        categoryName = templateCategoryService.getNameById(it.categoryId!!)
                                        commentNum = templateCommentService.count(
                                            KtQueryWrapper(TemplateComment::class.java)
                                                .eq(TemplateComment::templateId, it.id)
                                                .eq(TemplateComment::checkStatus, CheckStatusEnum.CHECK_PASS.code)
                                        )
                                            .toLong()
                                        requestStatusDesc = requestStatus?.run {
                                            when (this) {
                                                0 -> "处理中"
                                                1 -> "处理成功"
                                                else -> "处理失败"
                                            }
                                        } ?: "-"
                                        freeChannelNames = channelFreeTemplateMapper.selectList(KtQueryWrapper(ChannelFreeTemplate::class.java)
                                            .eq(ChannelFreeTemplate::templateId, it.id)
                                            .eq(ChannelFreeTemplate::templateType, it.type))
                                            .takeIf { it.isNotEmpty() }
                                            ?.run {
                                                channelManagerService.listByIds(map { it.channelId })
                                                    .takeIf { it.isNotEmpty() }
                                                    ?.run {
                                                        joinToString { it.name!! }
                                                    }
                                            }
                                    }
                                }
                            }
                    }.pageInfo()
                }
        }

    override fun removeTemplate(ids: String): Data<Boolean> =
        Ok("移除成功", kotlin.run {
            ids.split(",").forEach {
                getById(it.toLong())?.run {
                    type.takeIf { it == 2 }?.let {
                        Sign.removeImageFaceTemplate(this.picTemplateId)
                    }
                    removeById(it.toLong())
                }
            }
            true
        })
}